﻿using Kinlo.Entitys;
using Kinlo.MESDocking;
using NPOI.OpenXmlFormats.Spreadsheet;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Models.Devices;
using UIWindows.Services.Context;
using UIWindows.Tools.Helper;
using UIWindows.Views;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;

namespace UIWindows.Services.PLC_MESHelper
{
    /// <summary>
    /// 卷芯上料左扫码
    /// </summary>
    //[Attributes.TaskClass(TaskTypes.卷芯上料左扫码)]
    public class CoilCoreLoadingLeftScanBarcode : HelperBase
    {
        PLCBase InjMachine { get; set; }
        MESWinderInRecord _mesWinderInRecord { get; set; }
        public CoilCoreLoadingLeftScanBarcode(
            DeviceInteractiveaddressStatic deviceInteractiveaddressStatic,
            DeviceClientModel deviceModel,
            TemporaryStatic temporaryStatic,
            ParameterStatic parameterStatic,
            DeviceConfigStatic deviceConfigStatic,
            SystemConfigStatic systemConfigStatic,
             HomeStatic homeStatic,
             Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog
            ) : base(deviceInteractiveaddressStatic, deviceModel, temporaryStatic, parameterStatic, deviceConfigStatic, systemConfigStatic, homeStatic, log, dialog)
        {
            InjMachine =  deviceModel.PLC;
            _mesWinderInRecord = new MESWinderInRecord(_log, _dialog);
        }
        public override Task Handle()
        {
            short testResult = 2;
            RunLog($"-卷芯上料左扫码开始");

            try
            {
                DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == _deviceModel.ServiceName
             && x.TaskType == TaskTypes.卷芯上料左扫码);
                if (device == null)
                {
                    RunLog($"-卷芯上料左扫码 触发设备位置找不到，请注意!!!", MessageLevelType.错误);
                    return Task.CompletedTask;
                }
                var barcode = ScanCode(_parameterStatic.RunParameter.Retries_Count_ScanCode, device.Communication, 1);
                if (string.IsNullOrWhiteSpace(barcode) || barcode.Contains("ERROR"))
                {
                    testResult = 2;
                    RunLog($"【左扫码】扫码失败");
                }
                else
                {
                    testResult = 1;
                    try
                    { 
                        var entityType = GetEntityType();
                        var entity = CreateEntityType<object>();

                        // 设置数据库表名
                        PropertyInfo tableNameProperty = entityType.Item2.GetProperty("TableName", BindingFlags.Static | BindingFlags.Public);
                        tableNameProperty.SetValue(entity, Convert.ChangeType($"{entityType.Item1.Name}_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}", tableNameProperty.PropertyType), null);


                        var dateNow = DateTime.Now;
                        var entityData = entity as CoilCoreLoadingData;
                        entityData.LoadInboundTime = dateNow;
                        entityData.AcquisitionTime= dateNow;
                        entityData.NumPerPallet = "256";
                        entityData.PalletNo = barcode;
                        entityData.Position = (int)ScanPositionType.左扫码;
                        entityData.Insert();

                        _homeStatic.AddBattery(entityData, machineInfo_Type);
                    }
                    catch (Exception ex)
                    {
                        RunLog($"插入数据库【左扫码】发生异常:{ex}");
                    }

                    //上传MES
                    if (_parameterStatic.DecideParameter.EnableMES)
                    {
                        MESWinderInRecordUpload(_mesWinderInRecord, barcode);
                    }
                       

                    //_homeStatic.AddInCoilCoreLoadingDataBattery(barcode, DateTime.Now, ScanPositionType.左扫码);

                    RunLog($"【左扫码】扫码成功：{barcode}");
                }
            }
            catch (Exception ex)
            {
                RunLog($"【左扫码】发生异常:{ex}");
            }
            finally
            {
                var r1 = InjMachine.Write("DM1101", new short[] { testResult });
                var r2 = InjMachine.Write("DM1100", new short[] { 1 });
                var r3 = InjMachine.Write("DM1000", new short[] { 0 });
                RunLog($"【左扫码】写结果信号 {testResult} {r1}.{r2}.{r3} {(r1 && r2 && r3 ? "成功" : "失败")}");
            }



            return Task.CompletedTask;

            //return Task.CompletedTask;
        }
        //public override Task Handle(DataContext context)
        //{
        //    _context = context;
        //    RunLog($"-[{context.DeviceIndex}] 开始");
        //    Models.Devices.DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == context.TaskType
        //       && x.DeviceType == context.DeviceType && x.Index == context.DeviceIndex);
        //    if(device == null)
        //    {
        //        RunLog($"-[{context.DeviceIndex}] 触发设备位置找不到，请注意!!!", MessageLevelType.错误);
        //        return Task.CompletedTask;
        //    }
        //    var barcode = ScanCode(_parameterStatic.RunParameter.Retries_Count_ScanCode, device.Communication, context.DeviceIndex);

        //    return Task.CompletedTask;
        //}
    }
}
